package com.tec.security.utils.response.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;

/**
 * [Sa-Token 权限认证] 配置类
 */
@Configuration
public class SecurityConfig implements WebMvcConfigurer {

    /**
     * 注册 [Sa-Token全局过滤器]
     */
    @Bean
    public SaServletFilter getSaServletFilter(HttpServletRequest request) {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/file/images/**")
                // swagger
                .addExclude("/doc.html")
                .addExclude("/swagger-ui/index.html/**")
                .addExclude("/swagger-resources/**")
                .addExclude("/v2/**")
                .addExclude("/webjars/**")
                //账号相关
                .addExclude("/user/signup")
                .addExclude("/user/isLogin")
                .addExclude("/user/foundPassword")
                //邮件
                .addExclude("/Mail/SignupMail")
                .addExclude("/Mail/ResetMail")
                //网站首页
                .addExclude("/WWW/**")

                // 认证函数: 每次请求执行
                .setAuth(obj -> {
                    SaRouter.match("/**", "/user/doLogin", StpUtil::checkLogin);
                })

                // 异常处理函数：每次认证函数发生异常时执行此函数
                .setError(e -> SaResult.get(403,"无访问权限",null))

                .setBeforeAuth(r -> {
                    // ---------- 设置一些安全响应头 ----------
                    SaHolder.getResponse()
                            .setHeader("Content-Type","application/json;charset=utf-8")
                            // 服务器名称
                            .setServer("tec-gui")
                            // 是否可以在iframe显示视图： DENY=不可以 | SAMEORIGIN=同域下可以 | ALLOW-FROM uri=指定域名下可以
                            .setHeader("X-Frame-Options", "SAMEORIGIN")
                            // 是否启用浏览器默认XSS防护： 0=禁用 | 1=启用 | 1; mode=block 启用, 并在检查到XSS攻击时，停止渲染页面
                            .setHeader("X-XSS-Protection", "1; mode=block")
                            // 禁用浏览器内容嗅探
                            .setHeader("X-Content-Type-Options", "nosniff");
                });
    }
}

